import { reqGetcate,reqGetgoods,reqCartadd} from "../../request/api";
//初始值
const initState = {
  //初始化数据
  //商品分类数据
  getcate:[],
  //分类商品
  getgoods:[],
  //购物车添加
  cartadd:[]
  
};

//actionTypes
const types = {
  //修改数据 type
  CHANGE_GETCATE: "HOME_CHANGE_GETCATE",
  CHANGE_GETGOODS: "HOME_CHANGE_GETGOODS",
  CHANGE_CARTADD: "SHOP_CHANGE_CARTADD",
};

//reducer 修改数据
const reducer = (state = initState, action) => {
  switch (action.type) {
    case types.CHANGE_GETCATE:
      return {
        ...state,
        getcate: action.getcate,
      };
    case types.CHANGE_GETGOODS:
      return {
        ...state,
        getgoods: action.getgoods,
      };
    case types.CHANGE_CARTADD:
        return {
          ...state,
          cartadd:action.cartadd,
        };
    default:
      return state;
  }
};
//actionCreators组件派发的动作
export const actions = {
  changeGetcate: (getcate) => ({ type: types.CHANGE_GETCATE, getcate}),
  changeGetgoods: (getgoods) => ({ type: types.CHANGE_GETGOODS, getgoods}),
  changeCartadd: (cartadd) => ({ type: types.CHANGE_CARTADD, cartadd}),
  
  //请求 异步操作
  //
  reqGetcate: () => (dispatch, getState) => {
    reqGetcate().then((res) => {
        if(res.data.code===200){
             //存信息
          dispatch(actions.changeGetcate(res.data.list))
        }
    });
  },
  //分类商品
  reqGetgoods: (id) => (dispatch, getState) => {
    reqGetgoods({fid:id}).then((res) => {
        if(res.data.code===200){
             //存信息
          dispatch(actions.changeGetgoods(res.data.list))
        }
    });
  },
  //购物车添加
  reqCartadd: (goodsid) => (dispatch, getState) => {
    let uid=JSON.parse(sessionStorage.getItem('info')).uid;

    reqCartadd({uid:uid,goodsid:goodsid,type:1,num:1}).then((res) => {
      if(res.data.code===200){
           //存信息
        dispatch(actions.changeCartadd(res.data.list))
      }
  });
},
  
};

//selectors导出数据
export const getGetcate = state => state.cate.getcate;
export const getGetgoods = state => state.cate.getgoods;
export const getCartadd = state => state.cate.cartadd;


export default reducer;
